# -*- coding:utf-8 -*-
"""
You are given two non-empty linked lists representing two non-negative integers. 
The digits are stored in reverse order and each of their nodes contain a single digit. 
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
"""
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None


def islarge(sumnum):
    if sumnum < 10:
        return (0, sumnum)
    else:
        divisor, mod = divmod(sumnum, 10)
        return (divisor, mod)


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 and l2:
            sumnum = l1.val+l2.val
            divisor, mod = islarge(sumnum)
            sumnum = mod
            head = ListNode(sumnum)
            tail = head
            l1 = l1.next
            l2 = l2.next
            while l1 and l2:
                if divisor != 0:
                    sumnum = l1.val+l2.val+divisor
                else:
                    sumnum = l1.val + l2.val
                divisor, mod = islarge(sumnum)
                sumnum = mod
                sum_ = ListNode(sumnum)
                tail.next = sum_
                tail = tail.next
                l1 = l1.next
                l2 = l2.next
            while l1:
                if divisor != 0:
                    sumnum = l1.val+divisor
                else:
                    sumnum = l1.val
                divisor, mod = islarge(sumnum)
                sumnum = mod
                sum_ = ListNode(sumnum)
                tail.next = sum_
                tail = tail.next
                l1 = l1.next
            while l2:
                if divisor != 0:
                    sumnum = l2.val+divisor
                else:
                    sumnum = l2.val
                divisor, mod = islarge(sumnum)
                sumnum = mod
                sum_ = ListNode(sumnum)
                tail.next = sum_
                tail = tail.next
                l2 = l2.next
            if divisor != 0:
                sum_ = ListNode(divisor)
                tail.next = sum_
        elif l1:
            head = l1
        elif l2:
            head = l2
        return head